$(function() {
    var refreshHourRoomList = function (datas) {
        var roomInfos = datas;
        if (roomInfos.length === 0) {
            $('#hourRoomList').html('');
            $('#hourRoomListBodyEmpty').removeClass('hidden');
        } else {
            $('#hourRoomListBodyEmpty').addClass('hidden');
            var templateHTML = $($('#templateHourRoom').clone().html());
            var roomsHTML = '';
            $.each(roomInfos, function (key, roomInfo) {
                templateHTML.attr('data-value', key);
                templateHTML.find('.roomTypeName').text(roomInfo.roomtype);
                var roomNameLength = roomInfo.roomname.length;
                var roomnameHTML = '';
                var roomNumbers = '';
                for (i = 0; i < roomNameLength; i++) {
                    roomNumbers += roomInfo.roomid[i] + ',';
                    roomnameHTML += '<div class="roomNameTag" data-value="' + roomInfo.roomid[i] + '">' + roomInfo.roomname[i] + '</div>';
                }
                templateHTML.find('.roomNumbers').attr('data-number', roomNumbers.slice(0, -1));
                templateHTML.find('.roomNumbers').html(roomnameHTML);
                var price = '';
                for (var i = 0; i < roomInfo.price.length; i++) {
                    templateHTML.find('.roomTypePrice').eq([i]).text(roomInfo.price[i]['price']);
                }
                templateHTML.find('.roomhour').text(roomInfo.hour + lang('hour'));
                templateHTML.find('.roomcount').text(roomInfo.count + lang('room.jian'));
                roomsHTML += templateHTML.prop('outerHTML');
            });
            $('#hourRoomList').html(roomsHTML);
        }
    };

    $('.room-tab-hour').click(function () {
        var $me = $(this);
        ajaxRequest('/Home/HourRoom/getHourRoomInit', {hotel: window.currentHotel}, 'POST', function (data) {
            data = data.data;
            if (data === false) {
                $('#setHourRoomModal').modal('show');
            } else {
                roomInit = data.roomInit;
                if (roomInit.sechour != 0) {
                    $('.addFourHourLabel').removeClass('hidden');
                }
                $('#hour-room-info').text(lang('time.duration') + roomInit.checkintime + ':00 - ' + roomInit.checkouttime + ':00');
                $me.blur().addClass('btn-primary').siblings().removeClass('btn-primary');
                $('#room-hour').removeClass('hidden').siblings(":not(':first')").addClass('hidden');
                $('.hotel-content').removeClass('hidden');
                refreshHourRoomList(data.roomList);
                $('#content-panel-show').removeClass('hidden');
            }
        }, function(error){
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });
    });
    $('.plus-select-time').click(function () {
        $('#selectSecTime').removeClass('hidden');
        $(this).addClass('hidden');
    })
    $("#hourRoomStartTime").change(function () {
        var startTime = $(this).val();
        var hourRoomEndTimeId = $('#hourRoomEndTime');
        hourRoomEndTimeId.find('option').remove();
        if (startTime.length == 0) {
            hourRoomEndTimeId.append("<option value=''>" + lang('please.select') + "</option>");
            return true;
        }
        for (var i = parseInt(startTime) + 1; i <= 24; i++) {
            hourRoomEndTimeId.append("<option value='" + i + "'>" + appendZero(i) + ":00</option>");
        }
    });
    $('#init-hour-room').click(function () {
        var hourRoomStartTime = $('#hourRoomStartTime').val();
        if (hourRoomStartTime.length == 0) {
            $('#confirmRoomInitModal').modal('hide');
            $('#set_init_hour_info').text(lang('starttime.select'));
            return;
        }
        var hourRoomEndTime = $('#hourRoomEndTime').val();
        if (hourRoomEndTime.length == 0) {
            $('#confirmRoomInitModal').modal('hide');
            $('#set_init_hour_info').text(lang('endtime.select'));
            return;
        }
        var params = {
            checkinTime: hourRoomStartTime,
            checkoutTime: hourRoomEndTime,
            hotel: window.currentHotel,
        };
        ajaxRequest('/Home/HourRoom/initHourRoom', params, 'POST', function (data) {
            $('#confirmRoomInitModal').modal('hide');
            $('#setHourRoomModal').modal('hide');
            $('.room-tab-hour').blur().addClass('btn-primary').siblings().removeClass('btn-primary');
            $('#room-hour').removeClass('hidden').siblings(":not(':first')").addClass('hidden');
            $('#hour-room-info').text(lang('time.duration') + hourRoomStartTime + ':00 - ' + hourRoomEndTime + ':00');
        }, function (error) {
            error = error.responseJSON;
            $('#confirmRoomInitModal').modal('hide');
            $('#set_init_hour_info').text(error.info);
        });
    });
    window.hourRoomData = new Array();
    var hourRoomTagsData = [];

    var refreshHourRoom = function (modal) {
        var roomContainer = modal.find('.hourRoomTypeContainer');
        var addHourRoomTemplate = $('#addHourRoomTemplate');
        var data = roomContainer.data('amos.tag');
        // 分情况渲染页面
        if (hourRoomTagsData.length === 0) {
            modal.find('.hourRoomTypeGroup').addClass('hidden');
        } else {
            modal.find('.hourRoomTypeGroup').removeClass('hidden');
            if (!data) {
                roomContainer.tag({
                    removeAtSelected: true,
                    selectedTagClickable: false,
                    avaliable: hourRoomTagsData
                }).on('beforeSelected.amos.tag', function (e, value) {
                    var templete = $(addHourRoomTemplate.clone().html());
                    tempData = value.split(" ");
                    templete.find('.tag-text').text(tempData[0]).attr('data-value', tempData[1]);
                    var container = $(this);
                    var modal = container.parents('.modal');
                    modal.find('.roomNumContainer').append(templete.prop('outerHTML'));
                    // 如果房间是最后一个就隐藏，注意是beforeSelected，所以判断是1
                    if (container.find('.tag-avaliable-container .tag').length === 1) {
                        modal.find('.hourRoomTypeGroup').addClass('hidden');
                    }
                });
            } else {
                roomContainer.tag('resetAvaliable');
                roomContainer.tag('addAvaliable', hourRoomTagsData);
            }
        }
    }
// 添加钟点房模态框
    $('#addHourRoomModal').on('show.bs.modal', function (e) {
        var modal = $(this);
        var params = {
            hotel: window.currentHotel,
        };
        ajaxRequest('/Home/HourRoom/getRoomList', params, 'POST', function (data) {
            var data = data.data;
            var hourRoomTypeSelect = $('#hourRoomTypeSelect');
            hourRoomTypeSelect.children().remove();
            $('#addHourRoomNumContainer').children().remove();
            $.each(data, function (key, value) {
                hourRoomTypeSelect.append("<option value='" + value.roomTypeId + "'>" + value.roomTypeName + "</option>");
                window.hourRoomData[value.roomTypeId] = value.room;
            });
            hourRoomTagsData = [];
            $.each(data[0].room, function (index, value) {
                hourRoomTagsData.push({
                    id: value.name + ' ' + value.id,
                    name: value.name
                });
            });
            refreshHourRoom(modal);
        }, null);
    });

    //选择房型
    $('#hourRoomTypeSelect').change(function () {
        var hourRoomTypeId = $(this).val();
        var roomContainer = $('#addHourRoomModal').find('.hourRoomTypeContainer');
        hourRoomTagsData = [];
        $.each(window.hourRoomData[hourRoomTypeId], function (index, value) {
            hourRoomTagsData.push({
                id: value.name + ' ' + value.id,
                name: value.name
            });
        });
        $('#addHourRoomNumContainer').children().remove();
        refreshHourRoom($('#addHourRoomModal'));
    });

    //记录待添加的房间
    $('#hourRoomTagContainer').on('click', '.tag', function () {
        var roomTypeId = $('#hourRoomTypeSelect').val();
        var roomId = $(this).attr('data-value');
        var selectRoom = $.grep(hourRoomTagsData, function (data) {
            if (data.id == roomId) {
                return false;
            } else {
                return true;
            }
        });
        hourRoomTagsData = selectRoom;
    });

    //删除待添加的房间
    $('#addHourRoomModal').on('click', '.tag-minus', function () {
        var modal = $(this).parents('.modal');
        var roomId = $(this).siblings().attr('data-value');
        var roomName = $(this).siblings().text();
        var roomTypeId = $('#hourRoomTypeSelect').val();
        $(this).parent().remove();
        hourRoomTagsData.push({
            id: roomName + ' ' + roomId,
            name: roomName
        });
        refreshHourRoom(modal);
    });

    //添加钟点房
    $('#submitHourRoomAdd').on('click', function (e) {
        var roomInfoIds = [];
        var $me = $('#submitHourRoomAdd');
        var modal = $('#addHourRoomModal');
        var inputPrice = $('#addHourRoomModal').find('.price-input');
        $('#addHourRoomNumContainer').find('.hour-room-tag').each(function (k, v) {
            roomInfoIds[k] = $(this).find('.tag-text').data('value');
        });
        if (roomInfoIds.length == 0) {
            formInlineTip($(this), lang('room.select'), 0);
            return false;
        }
        var needBreak = false;
        var priceObj = [];
        inputPrice.each(function () {
            var price = $(this).val().replace(/^0(?=\d)/g, '');
            if ($.trim(price) == '') {
                formInlineTip($me, lang('price.select'), 0);
                needBreak = true;
                return false;
            } else if (price.length != '' && !window.commonRegexp.roomTypePrice.test(price)) {
                formInlineTip($me, lang('default.payVal'), 0);
                needBreak = true;
                return false;
            }
            priceObj.push(price);
        });
        if (needBreak) return;
        var roomTypeId = $('#hourRoomTypeSelect').val();
        var params = {
            'hotel': window.currentHotel,
            'price': priceObj,
            'roomInfoIds': roomInfoIds,
            'roomTypeId': roomTypeId,
            'hour': $("input[name='addCheckInHour']:checked").val(),
        }

        ajaxRequest('/Home/HourRoom/addHourRoom', params, 'POST', function (data) {
            refreshHourRoomList(data.data.roomList);
            $('#addHourRoomModal').modal('hide');
        }, null);
    });

    //修改钟点房模态框
    $('#editHourRoomModal').on('show.bs.modal', function (e) {
        var $me = $(e.relatedTarget),
            $parent = $me.parents('tr'),
            modal = $(this),
            roomTypeId = $parent.data('value'),
            inputPrice = modal.find('.price-input');
        waitForDelete = {};
        waitForAdd = {};
        formInlineTip($('#submitHourRoomEdit'), '');
        $('#editHourRoomName').val($parent.find('.roomTypeName').text());
        $('#editHourRoomName').data('id', roomTypeId);
        $('#editHourRoomPrice').val($parent.find('.roomTypePrice').text());
        ajaxRequest('/Home/HourRoom/getRoomByTypeId', {
            'hotel': window.currentHotel,
            'roomTypeId': roomTypeId,
        }, 'POST', function (data) {
            var data = data.data;
            var roomContainer = modal.find('.hourRoomTypeContainer');
            var addHourRoomTemplate = $('#addHourRoomTemplate');
            var templete = $(addHourRoomTemplate.clone().html());
            hourRoomTagsData = [];
            var roomIds = $parent.find('.roomNumbers').data('number').toString().split(',');
            modal.find('.roomNumContainer').html('');
            $.each(data.roomInfos, function (index, value) {
                if ($.inArray(value.id, roomIds) === -1) {
                    hourRoomTagsData.push({
                        id: value.name + ' ' + value.id,
                        name: value.name
                    });
                } else {
                    templete.find('.tag-text').text(value.name).attr('data-value', value.id);
                    modal.find('.roomNumContainer').append(templete.prop('outerHTML'));
                }
            });
            for (var i = 0; i < data.hourPrice.length; i++) {
                inputPrice.eq([i]).val(data.hourPrice[i]['price']);
            }
            refreshHourRoom(modal);
        }, null, $('#submitHourRoomEdit'));
    });
    //删除已添加的房间
    window.waitForDelete = {};
    $('#editHourRoomModal').on('click', '.tag-minus', function () {
        if ($('#editHourRoomNumContainer').find('.hour-room-tag').length == 1) {
            formInlineTip($('#submitHourRoomEdit'), lang('least.one'));
            return false;
        }
        var modal = $(this).parents('.modal');
        var roomId = $(this).siblings().attr('data-value');
        var roomName = $(this).siblings().text();
        var roomTypeId = modal.find('tr').data('value');
        waitForDelete[roomId] = roomId;
        $(this).parent().remove();
        hourRoomTagsData.push({
            id: roomName + ' ' + roomId,
            name: roomName
        });
        refreshHourRoom(modal);
    });
    //记录已添加的房间
    window.waitForAdd = {};
    $('#editHourRoomTagContainer').on('click', '.tag', function () {
        var roomId = $(this).attr('data-value');
        var selectRoom = $.grep(hourRoomTagsData, function (data) {
            if (data.id == roomId) {
                return false;
            } else {
                return true;
            }
        });
        hourRoomTagsData = selectRoom;
        roomId = roomId.split(' ')[1];
        waitForAdd[roomId] = roomId;
    });
    //修改钟点房房型
    $('#submitHourRoomEdit').on('click', function () {
        var modal = $('#editHourRoomModal');
        var $me = $(this);
        var inputPrice = modal.find('.price-input');
        var priceObj = [];
        var needBreak = false;
        inputPrice.each(function () {
            var price = $(this).val().replace(/^0(?=\d)/g, '');
            if ($.trim(price) == '') {
                formInlineTip($me, lang('price.select'), 0);
                needBreak = true;
                return false;
            } else if (price.length != '' && !window.commonRegexp.roomTypePrice.test(price)) {
                formInlineTip($me, lang('default.payVal'), 0);
                needBreak = true;
                return false;
            }
            priceObj.push(price);
        });
        if (needBreak) return;
        ajaxRequest('/Home/HourRoom/saveHourRoom', {
            'hotel': window.currentHotel,
            'waitForAdd': window.waitForAdd,
            'waitForDelete': window.waitForDelete,
            'price': priceObj,
            'hour': $("input[name='editCheckInHour']:checked").val(),
            'roomTypeId': $('#editHourRoomName').data('id'),
        }, 'POST', function (data) {
            refreshHourRoomList(data.data.roomList);
            modal.modal('hide');
        }, null, $(this));
    });
    //删除钟点房房型
    $('#deleteHourRoomModal').on('show.bs.modal', function (e) {
        var triggerTd = $(e.relatedTarget).parents('td'),
            triggerTr = triggerTd.parents('tr');
        var roomTypeId = triggerTr.data('value');
        var roomType = triggerTr.find('.roomTypeName').html();
        var roomNum = triggerTr.find('.roomNumbers').data('roomnumber');
        $('#deleteHourRoomModal .roomType').html(roomType);
        $('#submitHourRoomDelete').data('value', roomTypeId);
    });

    // 删除房型
    $('#submitHourRoomDelete').on('click', function (e) {
        var param = {
                hotel: window.currentHotel,
                roomTypeId: $(this).data('value'),
            },
            $me = $(this);
        ajaxRequest('/Home/HourRoom/deleteHourRoom', param, 'post', function (data) {
            refreshHourRoomList(data.data.roomList);
            $('#deleteHourRoomModal').modal('hide');
        }, function (error, $obj) {
            if (typeof error.responseJSON == 'undefined') {
                formInlineTip($obj, lang('tip.networkPoor'));
            } else {
                formInlineTip($obj, error.responseJSON.info);
            }
        }, $me);
    });
});
//1……9前补0
var appendZero = function (i) {
    if (i < 10) {
        return "0" + i;
    } else {
        return i;
    }
};